package com.coolw.core.spi;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * JDK 序列化、反序列化
 *
 * @author coolw
 * @date 2024/12/30 9:48
 */
public class JDKSerializer implements CustomerSerializer {

    @Override
    public byte[] serialize(Object data) {
        System.out.println("JDK serialize==========");
        if (data == null) {
            throw new IllegalArgumentException("JDK serialize obj is null");
        }

        try (ByteOutputStream bos = new ByteOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(data);
            return bos.getBytes();
        } catch (IOException e) {
            throw new RuntimeException("JDK serialize failed", e);
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        System.out.println("JDK deserialize==========");
        if (data == null) {
            throw new IllegalArgumentException("JDK deserialize data is null");
        }

        try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
             ObjectInputStream ois = new ObjectInputStream(bais)) {
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException("JDK deserialize failed", e);
        }
    }
}
